/*
 * @Author: songyingchun
 * @Date: 2023-04-18 10:09:32
 * @Description: 公共方法
 */

//千分位符
export const thousandthFormat = (num) => {
  if (num) {
    let number = Number(num).toFixed(2)
    let separatingSymbol = ',' //分隔符
    var numpart = String(number).split('.')
    for (let i = 0; i < numpart.length; i++) {
      numpart[i] = numpart[i].replace(new RegExp('(\\d)(?=(\\d{3})+$)', 'ig'), `$1${separatingSymbol || ''}`)
    }
    return numpart.join('.')
  } else {
    if (num === 0) {
      return 0
    } else {
      return '-'
    }
  }
}
export const getUrlParams = (params: any) => {
  const paramsStr: string[] = []
  const reg = new RegExp('%20', 'g') //浏览器默认把空格转化为%20  后台接受 +   所以手动转化为 +
  for (const key in params) {
    paramsStr.push(`${key}=${encodeURI(params[key]).replace(reg, '+')}`)
  }
  return paramsStr.join('&')
}
export const getUrlparam = (name: any) => {
  const after = window.location.hash.split('?')[1]
  if (after) {
    const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
    const r = after.match(reg)
    if (r != null) {
      return decodeURIComponent(r[2])
    } else {
      return null
    }
  } else {
    return null
  }
}
// 生成uuid
export const getUuid = () => {
  const s: any = []
  const hexDigits = '0123456789abcdef'
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-'

  const uuid = s.join('')
  return uuid
}
/*手机号码校验*/
export function checkMobile(tel: any) {
  return /^1[3456789]\d{9}$/.test(tel) ? true : false
}

export const dateFormat = (date: any, fmt = 'yyyy-MM-dd hh:mm:ss') => {
  if (!date) return ''
  const date1: any = new Date(date)

  const o: any = {
    'M+': date1.getMonth() + 1, // 月
    'd+': date1.getDate(), // 日
    'h+': date1.getHours(), // 小时
    'm+': date1.getMinutes(), // 分
    's+': date1.getSeconds(), // 秒
    'q+': Math.floor((date1.getMonth() + 3) / 3), // 季度S
    S: date1.getMilliseconds(), // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date1.getFullYear() + '').substr(4 - RegExp.$1.length))
  }

  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
    }
  }
  return fmt
}

export const keepTwoDecimal = (numb: number) => {
  // numb = Math.round(numb * 100) / 100
  const numb_str = numb?.toString()
  return numb_str.indexOf('.') > 0
    ? numb_str.replace(/\.\d*/i, (xiaoshu) => {
        return xiaoshu.length === 2 ? xiaoshu + '0' : xiaoshu.slice(0, 3)
      })
    : numb_str + '.00'
}

export const dictShow = (columns: any, cellValue: any, fieldName = 'value', labelName = 'label') => {
  let showText = cellValue
  const arrList: any = columns || []
  arrList.forEach((item: any) => {
    if (item[fieldName] == cellValue) {
      showText = item[labelName]
    }
  })
  return showText
}

/**
 * @description: 计算车龄
 * @return {string} 车龄
 * @param {number} year: 生产年份
 * @param {number} month：生产月份
 */
export const handleAutoAge = (year: number, month?: number) => {
  const now = new Date()
  const currentYear = now.getFullYear()
  const currentMonth = now.getMonth() + 1
  let result = ''
  if (month) {
    if (currentYear > year) {
      if (currentMonth > month) {
        result = `${currentYear - year}年${currentMonth - month}个月`
      } else if (currentMonth === month) {
        result = `${currentYear - year}年`
      } else {
        result = currentYear - year - 1 > 0 ? `${currentYear - year - 1}年${currentMonth + 12 - month}个月` : `${currentMonth + 12 - month}个月`
      }
    } else if (currentYear === year) {
      if (currentMonth > month) {
        result = `${currentMonth - month}个月`
      } else if (currentMonth === month) {
        result = ``
      } else {
        result = ``
      }
    } else {
      result = ''
    }
  } else {
    result = currentYear > year ? `${currentYear - year}年` : ``
  }
  return result
}
// 金额千分位格式处理
export function formatAmount(amount: number): string {
  amount = amount ? parseFloat(retainNum2(amount)) : 0
  return amount.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 保留两位小数，尾数不四舍五入
export const retainNum2 = (value) => {
  if (!value && value != 0) {
    return '-'
  } else {
    const tempVal = parseFloat(value).toFixed(4)
    const realVal = tempVal.substring(0, tempVal.length - 2)
    return realVal
  }
}

//计算总数
export const getTotal = (arr, key) => {
  return Number(
    arr
      .reduce((total, item) => {
        return total + Number(item[key] || 0)
      }, 0)
      .toFixed(2)
  )
}

// 手机号做脱敏处理
export const  phoneHide = (phone) => {
  let reg = /^(1[3-9][0-9])\d{4}(\d{4}$)/; // 定义手机号正则表达式
  phone = phone.replace(reg, '$1****$2');
  return phone; // 185****6696
}

